import { useState, useTransition } from 'react';
import { Button, Input } from 'antd';
 
function updateName(name:string) {
    console.log('表单正在更新', name)
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(undefined);
    }, 1000);
  });
}
 
export default function UpdateName() {
  const [name, setName] = useState('');
  const [error, setError] = useState(null);
  const [isPending, startTransition] = useTransition();
 
  const handleSubmit = () => {
    // startTransition 中的异步函数被称为 Action
    // 当 startTransition 被调用时 React 会自动变更 isPending 为 true
    // 同理，当函数执行完毕后 isPending 会自动变更为 false
    startTransition(async () => {
      const error:unknown = await updateName(name);
      if (error) {
        setError(error as unknown as null);
        return;
      }
      console.log('表单更新完毕')
    });
  };
 
  return (
    <div>
      <Input value={name} onChange={(event) => setName(event.target.value)} />
      <Button onClick={handleSubmit} disabled={isPending}>
        Update
      </Button>
      {error && <p>{error}</p>}
    </div>
  );

}

